package com.acme.bankapp.service.bank;

import java.util.List;

import com.acme.bankapp.domain.bank.*;

import java.io.*;

public class BankService {
	File serializedBankFile;

	public BankService(File serializedBankFile) {
		this.serializedBankFile = serializedBankFile;
	}

	public void addClient(Bank bank, Client client) {
		bank.addClient(client);
		saveBank(bank);
	}

	public Bank createBank() {
		Bank res = new Bank();
		saveBank(res);
		return res;
	}

	public Bank createBank(
			ClientRegistrationListener[] clientRegistrationListeners) {
		Bank res = new Bank(clientRegistrationListeners);
		saveBank(res);
		return res;
	}

	private void saveBank(Bank bank) {
		ObjectOutputStream output;
		try {
			output = new ObjectOutputStream(new FileOutputStream(
					serializedBankFile));
			output.writeObject(bank);
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.err
					.println("Something bad happened while serializing bank to file");
		}
	}

	public Bank readBank() throws IOException, ClassNotFoundException {
		ObjectInputStream input = new ObjectInputStream(new FileInputStream(
				serializedBankFile));
		Bank bank = (Bank) input.readObject();
		input.close();
		return bank;
	}

	public List<Client> getClients(Bank bank) {
		return bank.getClients();
	}

	public void printClients(Bank bank) {
		for (Client client : getClients(bank)) {
			System.out.println(client);
		}
	}

	public void printBalance(Bank bank) {
		for (Client client : getClients(bank)) {
			System.out.println(client.getClientSalutation() + "'s balance is "
					+ client.getAccount().getBalance());
		}
	}

	public void printMaximumAmountToWithdraw(Bank bank) {
		for (Client client : getClients(bank)) {
			System.out.println(client.getClientSalutation() + " can withdraw "
					+ client.getAccount().getMaximumAmountToWithdraw());
		}
	}

}
